//
//  UIButton+MessageBadge.m
//  SmartEstateCC
//
//  Created by pretang on 2018/3/20.
//  Copyright © 2018年 pretang. All rights reserved.
//

#import "UIButton+MessageBadge.h"
#import <objc/runtime.h>

@interface UnreadChangeObserver : NSObject
@property (nonatomic, copy) void (^onUnreadChange)(BOOL hasUnread);
@end

@implementation UnreadChangeObserver

- (void)dealloc
{
    [CTUnreadHandler.sharedInstance removeObserver:self forKeyPath:@"hasUnread"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [CTUnreadHandler.sharedInstance  addObserver:self forKeyPath:@"hasUnread" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"hasUnread"]) {
        if (self.onUnreadChange) {
            self.onUnreadChange(CTUnreadHandler.sharedInstance.hasUnread);
        }
    }
}

- (void)setOnUnreadChange:(void (^)(BOOL))onUnreadChange
{
    _onUnreadChange = onUnreadChange;
    if (self.onUnreadChange) {
        self.onUnreadChange(CTUnreadHandler.sharedInstance.hasUnread);
    }
}

@end


@implementation UIButton (MessageBadge)

static char UnreadDotKey;
static char UnreadChangeObserverKey;

- (void)bindMessageChange
{
    UILabel *dot = objc_getAssociatedObject(self, &UnreadDotKey);
    if (!dot) {
        dot = [[UILabel alloc] init];
        dot.backgroundColor = UIColor.redColor;
        dot.layer.masksToBounds = YES;
        dot.layer.cornerRadius = 3.f;
        [self addSubview:dot];
        [dot mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self);
            make.top.equalTo(self).mas_offset(@2);
            make.size.mas_equalTo(CGSizeMake(6.f, 6.f));
        }];
        objc_setAssociatedObject(self, &UnreadDotKey, self, OBJC_ASSOCIATION_ASSIGN);
    }
    UnreadChangeObserver *observer = objc_getAssociatedObject(self, &UnreadChangeObserverKey);
    if (!observer) {
        observer = [[UnreadChangeObserver alloc] init];
        objc_setAssociatedObject(self, &UnreadChangeObserverKey, self, OBJC_ASSOCIATION_RETAIN);
    }
    observer.onUnreadChange = ^(BOOL hasUnread) {
        dot.hidden = !hasUnread;
    };
}

@end
